//const { Enforcer } = require('casbin')

module.exports = option => {
    return async function (ctx, next) {
        /* const enforcer = await Enforcer.newEnforcer('authz_config/authz_model.conf', 'authz_config/authz_policy.csv')
        const sub = ctx.user.username; 
        const obj = ctx.originalUrl;
        const act = ctx.method;
        if (!enforcer.enforce(sub, obj, act)) {
            ctx.body = "没有权限"
            ctx.status = 403
        } else {
            await next()
        } */

        const obj = ctx.originalUrl;
        const act = ctx.method;
        if ((/api\/v1\/captch/.test(ctx.req.url)) ||
            (/api\/v1\/logout/.test(ctx.req.url)) ||
            (/api\/v1\/user/.test(ctx.req.url)) ||
            (/api\/v1\/login/.test(ctx.req.url))) {
            // 登录中
            await next();
        } else {
            const permissions = ctx.session.role.permissions
            //console.log(permissions);
            let flag = -1
            for (let i in permissions) {
                let permission = permissions[i]
                if (obj === permission.source && act === permission.action) {
                    flag = i
                    await next()
                    break
                }
            }
            if (flag === -1) {
                ctx.body = "没有权限"
                ctx.status = 403
            }
        }

    };
};

